import 'package:flutter/material.dart';

void main() => runApp(MyApp());

/// 选项卡(标签)：Tab、TabView、TabController
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
          primaryColor: Colors.yellow,
          // 店家tab按钮高亮颜色
          highlightColor: Color.fromRGBO(255, 255, 255, .5),
          // 水波纹颜色
          splashColor: Colors.white70),
      home: TabBarPage(),
      //DefaultControllerBody(),
    );
  }
}

// 使用默认的TabController
class DefaultControllerBody extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
        length: 5,
        child: Scaffold(
          appBar: AppBar(
            title: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Expanded(
                    child: TabBar(
                  //当元素多时，可以滑动
                  isScrollable: true,
                  tabs: <Widget>[
                    Tab(text: "本地"),
                    Tab(text: "全部"),
                    Tab(text: "热门"),
                    Tab(text: "体育"),
                    Tab(text: "音乐"),
                  ],
                  indicatorColor: Colors.blue,
                  labelColor: Colors.red,
                  unselectedLabelColor: Colors.white,
                  indicatorSize: TabBarIndicatorSize.label,
                ))
              ],
            ),
          ),
          body: TabBarView(children: [
            Text("本地"),
            Text("全部"),
            Text("热门"),
            Text("体育"),
            Text("音乐"),
          ]),
        ));
  }
}

// 使用TabController
class TabBarPage extends StatefulWidget {
  @override
  _TabBarPageState createState() => _TabBarPageState();
}

class _TabBarPageState extends State<TabBarPage>
    with SingleTickerProviderStateMixin {
  TabController _tabController;

  @override
  void initState() {
    super.initState();
    //实例化TabController
    _tabController = TabController(length: 2, vsync: this);
    _tabController.addListener(() {
      print('当前选中：${_tabController.index}');
    });
  }

  @override
  void dispose() {
    super.dispose();
    _tabController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("AppBar"),
        bottom: TabBar(
          unselectedLabelColor: Colors.black38,
          // 指示器
          indicatorColor: Colors.black54,
          // 指示器长度
          indicatorSize: TabBarIndicatorSize.label,
          indicatorWeight: 4.0,
          tabs: [Tab(text: "热销"), Tab(text: "库存")],
          controller: _tabController,
        ),
      ),
      body: TabBarView(
        children: [
          Text("热销"),
          Text("库存"),
        ],
        //appBar中与body中都需要添加Controller
        controller: _tabController,
      ),
    );
  }
}
